//
//  TAMTHomeController.swift
//  TAMeetApp
//
//  Created by Admin on 2024/11/29.
//

import UIKit
import SnapKit

class TAMTHomeController: UIViewController ,UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, TAMTHomeTopCellDelegate {
    
    var topDatas:[Any] = []
    var dataSources:[Any] = []
    
    lazy var tipLabel:UILabel = {
        let topLabel = UILabel()
        topLabel.text = "粉丝数需要大于99"
        topLabel.textColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)
        topLabel.font = .systemFont(ofSize: 12, weight: .medium)
        return topLabel
    }()
    
    
    // MARK: - Properties
    private lazy var topCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: self.view.width, height: 148)
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 0

        let collectionView = UICollectionView(frame: CGRect(x: 0, y: TAMTAppUtils.shared.statusBarHeight, width: self.view.width, height: 148), collectionViewLayout: layout)
        collectionView.contentInsetAdjustmentBehavior = .never
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        collectionView.register(TAMTHomeTopCell.self, forCellWithReuseIdentifier: "top.cell")
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    
    private lazy var listCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: self.view.width, height: 120)
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 16
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)

        let collectionView = UICollectionView(frame: CGRect(x: 0, y: CGRectGetMaxY(self.appView.frame) + 16, width: self.view.width, height: self.view.height - CGRectGetMaxY(self.appView.frame) - 49 - TAMTAppUtils.shared.safeAreaInsets.bottom - 16), collectionViewLayout: layout)
        collectionView.contentInsetAdjustmentBehavior = .never
        collectionView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor(red: 246/255.0, green: 247/255.0, blue: 248/255.0, alpha: 1);
        collectionView.register(TAMTHomeCell.self, forCellWithReuseIdentifier: "home.cell")
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    
    lazy var appView:UIView = {
        let app = UIView()
        app.frame = CGRectMake(0, CGRectGetMaxY(self.topCollectionView.frame) + 16, self.view.width, 50)
        
        let topLabel = UILabel()
        topLabel.text = "他遇社团"
        topLabel.textColor = UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1)
        topLabel.font = .systemFont(ofSize: 18, weight: .medium)
        app.addSubview(topLabel)
        topLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.leading.equalTo(16)
        }
        
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "add"), for: .normal)
        btn.addTarget(self, action: #selector(appOnAddAction), for: .touchUpInside)
        app.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.trailing.equalTo(-15)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 28, height: 28))
        }
        
        return app
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor(red: 246/255.0, green: 247/255.0, blue: 248/255.0, alpha: 1);
        let topView = UIImageView(image: UIImage(named: "home_top_bg"))
        self.view.addSubview(topView)
        topView.snp.makeConstraints { make in
            make.leading.trailing.top.equalToSuperview()
            make.height.equalTo(topView.snp.width).multipliedBy(172.5/375)
        }
        
        view.addSubview(topCollectionView)
        view.addSubview(appView)
        view.addSubview(listCollectionView)
        
        requestAPI()
    }
    
    @objc func onRoomAction() {
        APPopupView.hidden { [weak self] in
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                strongSelf.showKnonw(text: "你暂时还没有加入社团或创建社团，同时社团社团群聊只能由团长或者副团长创建才能使用", btnText: "去创建")
            }
        }
    }
    
    func didOnMoreAction() {
        showKnonw(text: "如内容引人不适，可进行投诉，投诉审查之后，如有问题，会进行下架，同时对该用户做出处罚", btnText: "举报")
    }
    
    func showKnonw(text:String, btnText:String) {
        let bottomView = UIView()
        bottomView.size = CGSize(width: 320, height: 220)
        bottomView.backgroundColor = .white
        bottomView.layer.cornerRadius = 16
        bottomView.layer.masksToBounds = true
        
        let topLabel = UILabel()
        topLabel.text = "温馨提示"
        topLabel.textColor = UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1)
        topLabel.font = .systemFont(ofSize: 16, weight: .medium)
        bottomView.addSubview(topLabel)
        topLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(20)
        }
        
        let view1 = UIView()
        view1.backgroundColor = UIColor(red: 246/255.0, green: 246/255.0, blue: 246/255.0, alpha: 1)
        bottomView.addSubview(view1)
        view1.snp.makeConstraints { make in
            make.bottom.centerX.equalToSuperview()
            make.width.equalTo(1)
            make.height.equalTo(55)
        }
        
        let view2 = UIView()
        view2.backgroundColor = UIColor(red: 246/255.0, green: 246/255.0, blue: 246/255.0, alpha: 1)
        bottomView.addSubview(view2)
        view2.snp.makeConstraints { make in
            make.bottom.equalTo(view1.snp.top)
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(1)
        }

        let topLabel1 = UILabel()
        topLabel1.attributedText = text.attributedStringWithlineSpacing(5.0, textColor: UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1), font: UIFont.systemFont(ofSize: 16, weight: .regular))
        topLabel1.numberOfLines = 0
        topLabel1.textAlignment = .center
        bottomView.addSubview(topLabel1)
        topLabel1.snp.makeConstraints { make in
            make.leading.equalTo(20)
            make.trailing.equalTo(-20)
            make.top.equalTo(topLabel.snp.bottom).offset(20)
        }
        
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.setTitle(btnText, for: .normal)
        leftBtn.setTitleColor(TAMTAppUtils.shared.mainColor, for: .normal)
        leftBtn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        leftBtn.addTarget(self, action: #selector(onCreareAction(btn: )), for: .touchUpInside)
        bottomView.addSubview(leftBtn)
        leftBtn.snp.makeConstraints { make in
            make.trailing.bottom.equalToSuperview()
            make.height.equalTo(54)
            make.left.equalTo(view1.snp.right)
        }
        
        let leftBtn1 = UIButton(type: .custom)
        leftBtn1.setTitle("我知道了", for: .normal)
        leftBtn1.setTitleColor(UIColor(red: 184/255.0, green: 187/255.0, blue: 190/255.0, alpha: 1), for: .normal)
        leftBtn1.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        leftBtn1.addTarget(self, action: #selector(onHidenAction), for: .touchUpInside)
        bottomView.addSubview(leftBtn1)
        leftBtn1.snp.makeConstraints { make in
            make.leading.bottom.equalToSuperview()
            make.height.equalTo(54)
            make.right.equalTo(view1.snp.left)
        }
        
        let popup = APPopupView(contentView: bottomView, position: .center, contentWidth: bottomView.width, contentHeight: bottomView.height)
        popup.show()
    }
    
    @objc func onCreareAction(btn:UIButton) {
        if btn.currentTitle == "去创建" {
            APPopupView.hidden { [weak self] in
                guard let strongSelf = self else { return }
                DispatchQueue.main.async {
                    strongSelf.navigationController?.pushViewController(TAMTCreateGroupController(), animated: true)
                }
            }
        }
        else if btn.currentTitle == "举报" {
            
        }
        
    }
    
    @objc func onHidenAction() {
        APPopupView.hidden()
    }
    
    @objc func appOnAddAction() {
        let bottomView = UIView()
        bottomView.size = CGSize(width: self.view.width, height: 160+TAMTAppUtils.shared.safeAreaInsets.bottom)
        bottomView.backgroundColor = .white
        
        bottomView.roundCorners(corners: [.topRight, .topLeft], radius: 16)
        
        let topLabel = UILabel()
        topLabel.text = "创建中心"
        topLabel.textColor = UIColor(red: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1)
        topLabel.font = .systemFont(ofSize: 16, weight: .medium)
        bottomView.addSubview(topLabel)
        topLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(20)
        }
        
        
        let rightBtn = UIButton(type: .custom)
        rightBtn.setBackgroundImage(UIImage(named: "btn_left"), for: .normal)
        rightBtn.contentHorizontalAlignment = .right
        rightBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 12)
        rightBtn.setImage(UIImage(named: "add_white"), for: .normal)
        rightBtn.addTarget(self, action: #selector(onCreareAction(btn: )), for: .touchUpInside)
        bottomView.addSubview(rightBtn)
        rightBtn.snp.makeConstraints { make in
            make.trailing.equalTo(-12)
            make.top.equalTo(topLabel.snp.bottom).offset(20)
            make.size.equalTo(CGSize(width: 240, height: 90))
        }
        
        rightBtn.addSubview(tipLabel)
        tipLabel.snp.makeConstraints { make in
            make.leading.equalTo(12)
            make.top.equalTo(50)
        }
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.setBackgroundImage(UIImage(named: "left"), for: .normal)
        leftBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 12)
        leftBtn.setTitle("社团群聊", for: .normal)
        leftBtn.setTitleColor(.white, for: .normal)
        leftBtn.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        leftBtn.contentHorizontalAlignment = .left
        leftBtn.contentVerticalAlignment = .top
        leftBtn.addTarget(self, action: #selector(onRoomAction), for: .touchUpInside)
        leftBtn.titleEdgeInsets = UIEdgeInsets(top: 12, left: 12, bottom: 0, right: 0)
        bottomView.addSubview(leftBtn)
        leftBtn.snp.makeConstraints { make in
            make.leading.equalTo(12)
            make.top.equalTo(rightBtn)
            make.right.equalTo(rightBtn.snp.left).offset(-12)
        }
        
        let topLabel1 = UILabel()
        topLabel1.text = "未开通"
        topLabel1.textColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1)
        topLabel1.font = .systemFont(ofSize: 12, weight: .regular)
        leftBtn.addSubview(topLabel1)
        topLabel1.snp.makeConstraints { make in
            make.leading.equalTo(12)
            make.top.equalTo(50)
        }
        
        
        let imgView = UIImageView()
        imgView.sd_setImage(with: NSURL(string: "https://static.aipiaxi.com/image/2024/09/Ft6NK3z0l_tTTnVQfXft_HMXGaG_.png") as URL?, placeholderImage: placeImage)
        leftBtn.addSubview(imgView)
        imgView.snp.makeConstraints { make in
            make.trailing.equalTo(-12)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 45, height: 45))
        }

        let popup = APPopupView(contentView: bottomView, position: .bottom, contentWidth: 300, contentHeight: bottomView.height)
        popup.show()

    }
    
    // 请求 API 的方法
    func requestAPI() {
        
        TAMTAppUtils.appRequestAPI(api: "https://result.eolink.com/pbpvFEK3621e972473e4d633d6f07cac62524668faa11dd?uri=/home/top/list") {[weak self] json, error in
            guard let strongSelf = self else { return }
            
            let jsonData = json?["data"] as? [String: Any]
            
            let app = NSArray.yy_modelArray(with: TAMTHomeTopBsShowingList.self, json: jsonData!["bsShowingList"] ?? [])
            strongSelf.topDatas = app ?? []
            // 在主线程上更新 UI
            DispatchQueue.main.async {
                strongSelf.topCollectionView.reloadData()
            }
        }
        
        
        TAMTAppUtils.appRequestAPI(api: "https://result.eolink.com/pbpvFEK3621e972473e4d633d6f07cac62524668faa11dd?uri=/home/list") {[weak self] json, error in
            guard let strongSelf = self else { return }
            
            let app = NSArray.yy_modelArray(with: TAMTHomeItem.self, json: json!["items"] ?? [])
            strongSelf.dataSources = app ?? []

            DispatchQueue.main.async {
                strongSelf.listCollectionView.reloadData()
            }
        }
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == topCollectionView {
            return topDatas.count
        }
        return dataSources.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        
        if collectionView == topCollectionView {
            guard let cell = collectionView.dequeueReusableCell(
                withReuseIdentifier: String(describing: "top.cell"),
                for: indexPath
            ) as? TAMTHomeTopCell else {
                fatalError("Unable to dequeue YOUfanGoddessGridsCell")
            }
            cell.model = topDatas[indexPath.row] as? TAMTHomeTopBsShowingList
            cell.delegate = self
            
            // 配置 cell
            return cell
        }
        else {
            guard let cell = collectionView.dequeueReusableCell(
                withReuseIdentifier: String(describing: "home.cell"),
                for: indexPath
            ) as? TAMTHomeCell else {
                fatalError("Unable to dequeue TAMTHomeCell")
            }
            cell.index = indexPath.row
            cell.model = dataSources[indexPath.row] as? TAMTHomeItem
            
            // 配置 cell
            return cell
        }
    }

    // MARK: - UICollectionView Delegate Methods
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("Selected item at \(indexPath)")
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionView == self.topCollectionView {
            return CGSize(width: view.width, height: 148)
        }
        else {
            let model = dataSources[indexPath.row] as? TAMTHomeItem
            return CGSize(width: view.width, height: model!.height)
        }
    }
}
